//
//  BowenPreviewViewController.m
//  YiqiMobile
//
//  Created by henry on 13-4-21.
//  Copyright (c) 2013年 henry. All rights reserved.
//

#import "BowenPreviewViewController.h"
#import "BowenPreviewCell.h"
#import "BowenPreviewTitleCell.h"
#import "Utility.h"
#import "Config.h"
#import "MBProgressHUD.h"
#import "JSON.h"
#import "DefineAction.h"

static NSString *cellIdentity1 = @"BowenPreviewCell";
static NSString *cellIdentity2 = @"BowenPreviewTitleCell";

@interface BowenPreviewViewController ()

@end

@implementation BowenPreviewViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
   
	// Do any additional setup after loading the view.
    float height=367;
    if (iPhone5) {
        height+=88;
    }
    self.mytableView=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, height+49)];
    self.mytableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    //self.mytableView.showsVerticalScrollIndicator=NO;
    self.mytableView.dataSource=self;
    self.mytableView.delegate=self;
    [self.view addSubview:self.mytableView];
    self.arrayList=[NSMutableArray array];
}

-(void) loadDataFromServer:(NSString*)bowenid{
    [[MBProgressHUD showHUDAddedTo:self.view  animated:NO] setDetailsLabelText:LOADING_TITLE_DEFAULT];
    NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@",[Utility getServerUrl],BOWENACTION,bowenid];
    
    self.request=[[URLRequest alloc] initWithPostURL:url andDelegate:self andPostData:nil andFile:nil];
    [self.request startLoadData];
}

- (void)requestFinished:(id)context{
    [MBProgressHUD hideAllHUDsForView:self.view  animated:NO];
    @try{
        NSDictionary *result=[context JSONValue];
        if (result!=nil&&[[result objectForKey:@"code"] integerValue]==0) {
            if ([[result  objectForKey:@"method"] isEqual:BOWENACTION]) {
                [self.arrayList removeAllObjects];
                [self.arrayList addObjectsFromArray:[result objectForKey:@"list"]];
                self.bowenDict=[NSMutableDictionary dictionaryWithDictionary:[result objectForKey:@"data"]];
                [self.mytableView reloadData];
                
            }
        }else{
            [Utility customAlertWithMsg:PROCESSERROE andTitle:ALRRTTITLE andDelagate:nil];
        }
    }@catch (NSException *e) {
        [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
    }
}

- (void)requestFailed:(id)context error:(NSString *)error{
    [Utility customAlertWithMsg:NETWORTERROE andTitle:ALRRTTITLE andDelagate:nil];
}



//指定有多少个分区(Section)，默认为1
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.arrayList count]+1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 38.0f;
}

//表视图委托
#pragma mark - Tableview datasource & delegates
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 38)];
    view.backgroundColor=[UIColor whiteColor];
    UILabel *label1=[Utility detailTextLabel:CGRectMake(12, 15, 50, 20) andFontSize:15];
    label1.textColor=UIColorFromRGB(0x666666);
    label1.text=@"Title:";
    [view addSubview:label1];
    
    UILabel *label2=[Utility detailTextLabel:CGRectMake(58, 15, 100, 20) andFontSize:15];
    label2.text=[self.bowenDict objectForKey:@"str2"];
     self.navigationItem.titleView=[Utility getTitleView:[self.bowenDict objectForKey:@"str2"]];
    [view addSubview:label2];
    
    UILabel *label3=[Utility detailTextLabel:CGRectMake(200, 15, 50, 20) andFontSize:15];
    label3.textColor=UIColorFromRGB(0x666666);
    label3.text=@"圈子:";
    [view addSubview:label3];
    
    UILabel *label4=[Utility detailTextLabel:CGRectMake(242, 15, 100, 20) andFontSize:15];
    
    label4.text=[self.bowenDict objectForKey:@"str10"];
    [view addSubview:label4];
    UILabel *line=[Utility detailTextLabel:CGRectMake(0, 37, 320, 1) andFontSize:1];
    line.backgroundColor=[UIColor colorWithRed:225.0/255 green:250.0/255 blue:250.0/255 alpha:1.0];
    [view addSubview:line];
    return view;

}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.frame.size.height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0) {
        BowenPreviewTitleCell *cell = (BowenPreviewTitleCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentity1];
        if (cell ==  nil) {
            cell = [[BowenPreviewTitleCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity1];
        }
        NSString *content=[self.bowenDict objectForKey:@"str7"];
        UIFont *font=[UIFont fontWithName:FONT_FAMILY size:15.0f];
        CGSize size=[Utility getStringSize:content font:font withMaxSize:CGSizeMake(300, 100)];
        cell.content.frame=CGRectMake(10, 10, 300, size.height);
        cell.content.numberOfLines=size.height/20;
        cell.content.text=content;
        if (1!=1) {//图片存在
            cell.frame=CGRectMake(0, 0, 320, size.height+185);
            cell.contentImage.hidden=NO;
             cell.contentImage.frame=CGRectMake(85, cell.content.frame.origin.y+cell.content.frame.size.height+12, 150, 90);
            cell.contentImage.image=[Utility imageNamed:@"keyboardButton.png"];
        }else{
            cell.frame=CGRectMake(0, 0, 320, size.height+85);
            cell.contentImage.hidden=YES;
            cell.contentImage.frame=CGRectMake(85, cell.content.frame.origin.y+cell.content.frame.size.height, 320, 0);
        }
       
        
        cell.plImage.frame=CGRectMake(75, cell.contentImage.frame.origin.y+cell.contentImage.frame.size.height+30, 17, 17);
         cell.fenxiangImage.frame=CGRectMake(145, cell.contentImage.frame.origin.y+cell.contentImage.frame.size.height+30, 17, 17);
         cell.shoucangImage.frame=CGRectMake(210, cell.contentImage.frame.origin.y+cell.contentImage.frame.size.height+30, 17, 17);
        
        cell.plLabel.frame=CGRectMake(95, cell.contentImage.frame.origin.y+cell.contentImage.frame.size.height+30, 40, 17);
        cell.fenxiangLabel.frame=CGRectMake(165, cell.contentImage.frame.origin.y+cell.contentImage.frame.size.height+30, 40, 17);
        cell.shoucangLabel.frame=CGRectMake(230, cell.contentImage.frame.origin.y+cell.contentImage.frame.size.height+30, 40, 17);
        if (self.bowenDict!=nil) {
            cell.plLabel.text=[NSString stringWithFormat:@"%@",[self.bowenDict objectForKey:@"count5"]];
            cell.fenxiangLabel.text=[NSString stringWithFormat:@"%@",[self.bowenDict objectForKey:@"count4"]];
            cell.shoucangLabel.text=[NSString stringWithFormat:@"%@",[self.bowenDict objectForKey:@"count6"]];
        }
        
        
        return cell;
        
    }else{
        
        BowenPreviewCell *cell = (BowenPreviewCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentity2];
        if (cell ==  nil) {
            cell = [[BowenPreviewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentity2];
        }
        
        NSDictionary *dict=[self.arrayList objectAtIndex:indexPath.row-1];
        cell.contentText.hidden=YES;
        cell.eMAsyncImageView.hidden=YES;
        cell.voiceButton.hidden=YES;
        switch ([[dict objectForKey:@"count2"] integerValue]) {
            case 1:{//文本
                cell.contentText.hidden=NO;
                UIFont *font=[UIFont fontWithName:FONT_FAMILY size:12.0f];
                CGSize size=[Utility getStringSize:[dict objectForKey:@"str5"] font:font withMaxSize:CGSizeMake(230, 100)];
                if (size.height>=60) {
                    cell.contentText.numberOfLines=3;
                    [cell setFrame:CGRectMake(0, 0, 320, 100)];
                }else{
                    cell.contentText.numberOfLines=(size.height/20);
                    [cell setFrame:CGRectMake(0, 0, 320, size.height+40)];
                }
                
                if (size.height>=60) {
                    cell.contentText.frame=CGRectMake(66, 36, 230, 60);
                }else{
                    cell.contentText.frame=CGRectMake(66, 36, 230, size.height);
                }
                cell.contentText.text=[dict objectForKey:@"str5"];
                break;
            }
            case 2:{//图片
                cell.eMAsyncImageView.hidden=NO;
                cell.eMAsyncImageView.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=1",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str1"]];
                cell.eMAsyncImageView.frame=CGRectMake(66,36,100,100);
                cell.eMAsyncImageView.imageId=[dict objectForKey:@"str1"];
                
                [cell setFrame:CGRectMake(0, 0, 320, cell.eMAsyncImageView.frame.size.height+40)];
                break;
            }
            case 3:{//语音
                cell.voiceButton.hidden=NO;
                cell.voiceButton.frame=CGRectMake(66, 36, 38, 38);
                [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateNormal];
                [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateSelected];
                [cell.voiceButton setImage:[UIImage imageNamed:@"yuyinButton.png"] forState:UIControlStateHighlighted];
                cell.voiceButton.tag=indexPath.row;
                [cell.voiceButton addTarget:self action:@selector(playmp3Action:) forControlEvents:UIControlEventTouchUpInside];
                [cell setFrame:CGRectMake(0, 0, 320, cell.voiceButton.frame.size.height+40)];
                break;
            }
            case 4:{//视频
                
                break;
            }
        }
         cell.nickName.text=[dict objectForKey:@"str3"];
         cell.logo.imageUrl=[NSString stringWithFormat:@"%@/%@?id=%@&type=3",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str4"]];
        return cell;
    }
}


-(IBAction)playmp3Action:(UIButton*)sender{
    voiceLoading=[[UIView alloc] initWithFrame:sender.frame];
    voiceLoading.backgroundColor=[UIColor colorWithRed:249.0/255 green:249.0/255 blue:249.0/255 alpha:1.0];
    UIActivityIndicatorView *activityIndicatorView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    activityIndicatorView.center=CGPointMake((sender.frame.size.width-20)/2, (sender.frame.size.height-30)/2);
    [activityIndicatorView startAnimating];
    [voiceLoading addSubview:activityIndicatorView];
    [sender  addSubview:voiceLoading];
    
    NSDictionary *dict=[self.arrayList objectAtIndex:[sender tag]-1];
    NSString *url=[NSString stringWithFormat:@"%@/%@?id=%@&type=2",[Utility  getServerUrl],DOWNFILEACTION,[dict objectForKey:@"str1"]];
    EMAsyncFile *eMAsyncFile=[[EMAsyncFile alloc] init];
    eMAsyncFile.imageIdKey=@"id";
    eMAsyncFile.delegate=self;
    [eMAsyncFile setImageUrl:url];
    
}
#pragma -mark EMAsyncFileDelegate
-(void) fileSuccess:(NSString*)url{
    [voiceLoading removeFromSuperview];
    self.voiceRecord=[[VoiceRecord alloc] init];
    self.voiceRecord.delegate=self;
    [self.voiceRecord playMp3Click:url];
    
}
-(void) fileFail:(NSString*)error{
    [voiceLoading removeFromSuperview];
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
